package com.xs.ahoi.hcxs.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.*;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.listener.AppTTSListener;
import com.xs.ahoi.hcxs.utils.ButterKnifeUtil;
import com.xs.ahoi.hcxs.utils.FileDownloadUtil;
import com.xs.ahoi.hcxs.utils.LogUtil;
import com.xs.ahoi.hcxs.utils.tts.TtsUtil;

import static com.xs.ahoi.hcxs.utils.Constants.SERVER_HOST;

/**
 * author: cdfuhuichao
 * date: 2019/7/30 16:15
 * path: com.xs.ahoi.hcxs.ui.fragment.BookCityFragment
 * description: 书城
 */
public class BookCityFragment extends Fragment {

    @BindView(R.id.webView)
    public WebView webView;

    private Unbinder unbinder;
    private String indexUrl = SERVER_HOST + "/static/app/category.html";
    private String errorUrl = "file:///android_asset/error.html";


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_city, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDomStorageEnabled(true);// 打开本地缓存提供JS调用,至关重要
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);// 实现8倍缓存
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);

//        webView.clearCache(true);
        // 允许js调用android方法
        webView.addJavascriptInterface(new AndroidJs(), "AndroidJs");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.e(url);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                LogUtil.e("onReceivedError: " + error.getDescription());
                webView.loadUrl(errorUrl);
            }
        });
        webView.setOnLongClickListener(v -> true);

        // 监听返回键，调用web页面的goBack方法
        webView.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    webView.loadUrl("javascript:goBack()");
                    return true;
                }
            }
            return false;
        });

        webView.loadUrl(indexUrl);
    }

    private void postLoadUrl(String url) {
        webView.post(() -> webView.loadUrl(url));
    }

    @Override
    public void onDestroy() {
        ButterKnifeUtil.unbind(unbinder);
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();

            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }

    class AndroidJs {
        @JavascriptInterface
        public void speak(String msg) {
            TtsUtil.getInstance().appSpeakStart(msg, new AppTTSListener() {
                @Override
                public void finish() {
                    postLoadUrl("javascript:playFinish()");
                }
            });
        }

        @JavascriptInterface
        public void speakStop() {
            TtsUtil.getInstance().appSpeakStop();
        }

        @JavascriptInterface
        public void download(String url, String fileName) {
            FileDownloadUtil.start(url, fileName);
        }
    }

//    //点击返回上一页面而不是退出浏览器
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
//            webView.goBack();
//            return true;
//        }
//
//        return super.onKeyDown(keyCode, event);
//    }

}
